
package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.utils.MinIOUtils;
import java.util.Map;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.system.domain.SysFile;
import com.ruoyi.system.service.ISysFileService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MinIOUtils minIOUtils;
    
    @Autowired
    private ISysFileService fileService;

    /**
     * 文件上传接口
     * @param file 文件
     * @return 文件标识
     */
    @PostMapping("/upload")
    public R<Map<String, String>> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "businessType", required = true) String businessType) {
        try {
            if (file == null || file.isEmpty()) {
                return R.fail("文件不能为空");
            }
            if (file.getSize() > 1073741824L) { // 1GB
                return R.fail("文件大小不能超过1GB");
            }
            if (StringUtils.isEmpty(businessType)) {
                return R.fail("业务类型不能为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.lastIndexOf(".") > 0) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 上传文件
            String fileKey = minIOUtils.uploadFile(file, fileExtension);
            
            // 记录文件信息
            SysFile sysFile = new SysFile();
            sysFile.setFileName(originalFilename);
            sysFile.setFileKey(fileKey);
            sysFile.setFileType(fileExtension);
            sysFile.setFileSize(file.getSize());
            sysFile.setCreateTime(new Date());
            sysFile.setBusinessType(businessType);
            Long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 1L;
            sysFile.setCreateBy(userId);
            sysFile.setStatus("0");
            fileService.recordFile(sysFile);
            
            // 返回包含下载URL和fileKey的完整信息
            return R.ok(Map.of(
                "url", "/file/download/" + fileKey,
                "fileKey", fileKey
            ));
        } catch (Exception e) {
            return R.fail("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件下载接口
     * @param fileId 文件标识
     * @return 文件流
     */
    @GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId, HttpServletResponse response) {
        try {
            InputStream inputStream = minIOUtils.downloadFile(fileId);
            
            // 根据文件扩展名设置Content-Type
            String contentType = "application/octet-stream";
            if (fileId.lastIndexOf(".") > 0) {
                String fileExtension = fileId.substring(fileId.lastIndexOf("."));
                if (isImageFile(fileExtension)) {
                    contentType = "image/" + fileExtension.substring(1);
                }
            }
            
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileId);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败：" + e.getMessage());
        }
    }

    /**
     * 图片预览接口
     * @param fileId 文件标识
     */
    @GetMapping("/preview/{fileId}")
    public void preview(@PathVariable String fileId, HttpServletResponse response) {
        try {
            InputStream inputStream = minIOUtils.downloadFile(fileId);
            
            // 检查是否为图片
            if (fileId.lastIndexOf(".") > 0) {
                String fileExtension = fileId.substring(fileId.lastIndexOf("."));
                if (isImageFile(fileExtension)) {
                    response.setContentType("image/" + fileExtension.substring(1));
                    IOUtils.copy(inputStream, response.getOutputStream());
                    response.flushBuffer();
                    inputStream.close();
                    return;
                }
            }
            
            throw new RuntimeException("文件不是图片类型");
        } catch (Exception e) {
            throw new RuntimeException("图片预览失败：" + e.getMessage());
        }
    }
    
    /**
     * 判断是否为图片文件
     */
    private boolean isImageFile(String fileExtension) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
        for (String ext : imageExtensions) {
            if (ext.equalsIgnoreCase(fileExtension)) {
                return true;
            }
        }
        return false;
    }
}
